package ru.gerunn.parsing.service;

import java.net.MalformedURLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFilenameFilter;

public class LogProvider {
	private SmbFile[] files;
	
	public LogProvider(String dir, final String prefix, final Timestamp timestamp) {
		try {
			NtlmPasswordAuthentication ntlmPasswordAuthentication = NtlmPasswordAuthentication.ANONYMOUS;
			SmbFile smbFile = new SmbFile(dir, ntlmPasswordAuthentication);
			if (smbFile.exists()) {
				SmbFilenameFilter smbFilenameFilter = new SmbFilenameFilter() {
					public boolean accept(SmbFile dir, String name) throws SmbException {
						boolean ret = false;
						try {
							if (name.startsWith(prefix)) {
								Pattern tsPattern = Pattern.compile("^" + Pattern.quote(prefix) + "-(\\d{4}-\\d{2}-\\d{2})_.*(-\\d{2}\\.\\d{2}\\.\\d{2}).*$");
								Matcher tsMatcher = tsPattern.matcher(name);
								if (tsMatcher.matches()) {
									String tsString = tsMatcher.group(1) + tsMatcher.group(2);
									Timestamp ts = null;
										ts = new Timestamp(new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss").parse(tsString).getTime());
									if (timestamp.compareTo(ts) <= 0 ) {
										ret = true;
									}
								}
							}
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						return ret;
					}
				};
				this.files = smbFile.listFiles(smbFilenameFilter);
				Arrays.sort(this.files, new Comparator<SmbFile>() {
					public int compare(SmbFile a, SmbFile b) {
						return a.getName().compareTo(b.getName());
					}
				});
			}
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SmbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public SmbFile[] getFiles() {
		return files;
	}
	
}
